package com.cn.appcore.config

import android.net.ParseException
import android.util.Log
import com.google.gson.JsonParseException
import com.google.gson.stream.MalformedJsonException
import org.apache.http.conn.ConnectTimeoutException
import org.json.JSONException
import retrofit2.HttpException
import java.net.ConnectException

/**
 * 描述　: 根据异常返回相关的错误信息工具类
 */
object ExceptionHandle {

    fun handleException(e: Throwable?): AppException {
        val ex: AppException
        e?.let {
            when {
                e is HttpException -> {
                    ex = AppException(Error.NETWORK_ERROR,e)
                    return ex
                }
                e is JsonParseException ||
                e is JSONException ||
                e is ParseException ||
                e.toString().startsWith("java.") ||
                e.toString().startsWith("com.google.gson") ||
                e is MalformedJsonException -> {
                    Log.d("hello","MalformedJsonException:${e.toString()}")
                    ex = AppException(Error.PARSE_ERROR,e)
                    return ex
                }
                e is ConnectException ||
                e.toString().startsWith("java.net.ConnectException") -> {
                    ex = AppException(Error.NETWORK_ERROR,e)
                    return ex
                }
                e is javax.net.ssl.SSLException -> {
                    ex = AppException(Error.SSL_ERROR,e)
                    return ex
                }
                e is ConnectTimeoutException -> {
                    ex = AppException(Error.TIMEOUT_ERROR,e)
                    return ex
                }
                e is java.net.SocketTimeoutException ||
                e.toString().contains("timeout") -> {
                    ex = AppException(Error.TIMEOUT_ERROR,e)
                    return ex
                }
                e is java.net.UnknownHostException ||
                e.toString().startsWith("java.net.UnknownHostException") -> {
                    ex = AppException(Error.TIMEOUT_ERROR,e)
                    return ex
                }
                e is AppException -> return e

                else -> {
                    ex = AppException(Error.UNKNOWN,e)
                    return ex
                }
            }
        }
        ex = AppException(Error.UNKNOWN,e)
        return ex
    }
}